package com.ubi.core.framework.queue;

import com.ubi.core.json.JsonConverter;
import org.springframework.data.redis.core.StringRedisTemplate;

public class RedisQueueImpl<T> implements Queue<T> {

    private String name;

    private JsonConverter jsonConverter;

    private StringRedisTemplate stringRedisTemplate;

    private Class<T> elementClass;

    @Override
    public void add(T t) {
        stringRedisTemplate.opsForList().leftPush(name, jsonConverter.toJson(t));
    }

    @Override
    public T poll() {
        String json = stringRedisTemplate.opsForList().rightPop(name);
        if (json == null) {
            return null;
        }
        return jsonConverter.toObject(json, elementClass);
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setJsonConverter(JsonConverter jsonConverter) {
        this.jsonConverter = jsonConverter;
    }

    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void setElementClass(Class<T> elementClass) {
        this.elementClass = elementClass;
    }
}
